using System;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using Object = UnityEngine.Object;

namespace uMVP.Dialog
{
    public interface IModelMessageDialog : IModelDialog
    {
        UniTask OpenAsync(string content);
    }

    public interface IDevelopModelMessageDialog : IModelMessageDialog
    {
    }

    public class DevelopModelMessageDialog : ModelMessageDialog, IDevelopModelMessageDialog
    {
        protected override string Path => "uMVP/DevelopModelMessageDialog";
    }

    public class ModelMessageDialog : ModelDialogBase, IModelMessageDialog
    {
        private GameObject _viewGameObject;
        private Text _text;
        private Button _closeButton;
        private UniTaskCompletionSource _completionSource;

        public async UniTask OpenAsync(string content)
        {
            await base.OpenAsync();
            _text.text = content;
            _completionSource = new UniTaskCompletionSource();
            await _completionSource.Task;
        }

        protected override UniTask OnOpenAsync()
        {
            var path = Path;
            var prefab = Resources.Load<GameObject>(path);
            if (prefab == null)
                throw new Exception($"预制体路径错误，请检查预制体路径，prefabPath:{path}");

            _viewGameObject = Object.Instantiate(prefab, Canvas.gameObject.transform);
            _text = _viewGameObject.GetComponentInChildren<Text>();
            _closeButton = _viewGameObject.GetComponentInChildren<Button>();
            _closeButton.onClick.AddListener(OnClose);
            return UniTask.CompletedTask;
        }

        protected virtual string Path => "uMVP/ModelMessageDialog";

        protected override UniTask OnCloseAsync()
        {
            if (_viewGameObject != null)
                Object.Destroy(_viewGameObject);
            if (_closeButton != null)
                _closeButton.onClick.RemoveAllListeners();
            return UniTask.CompletedTask;
        }

        private void OnClose()
        {
            CloseAsync().Forget();
            _completionSource.TrySetResult();
        }
    }
}